package middleware

import (
	"Godzilla/common/responses"
	"Godzilla/enum/code"
	"fmt"
	"github.com/labstack/echo/v4"
	"log"
	"net/http"
	"time"
)

// CalHandleTime 打印处理时间
func CalHandleTime(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) (err error) {
		start := time.Now()
		defer func() {
			fmt.Println("请求处理时间：", time.Since(start)/time.Millisecond)
		}()
		err = next(c)
		return
	}
}

// Auth 校验token
func Auth() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			token := c.Request().Header.Get("token")
			//TODO 从redis或者mysql查询token校验
			if token == "" {
				return c.JSON(http.StatusOK, responses.Response(code.PermissionError, "token有误", ""))
			}
			return next(c)
		}
	}
}

func Rbac() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			//获取路由
			uri := c.Request().RequestURI
			log.Println(uri)
			method := c.Request().Method
			log.Println(method)
			//判断rbac中的路由此处的路由匹配规则
			r := c.Path()
			log.Println(r)
			//查询mysql或者redis没有权限则返回错误
			//if "" == "" {
			//	return c.JSON(http.StatusOK, responses.Response(code.PermissionError, "权限错误", ""))
			//}
			return next(c)
		}
	}
}

